
let collectionData = []
let conditionForm = {}  //条件form
let urlp = 1  //页数

let robotstatenum1 = 0
let robotstatenum2 = 0
let robotputinsize = 50

let robotputinnum = 0
let errorrobotputinnum = 0

let prevtimestampRobot = 0
let setIntervalstartRobot = 0

function runEverySecond() {
    setInterval(function () {
        if (prevtimestampRobot != 0 && collectionData.length > 0 && setIntervalstartRobot == 0) {
            let result = isWithin30Seconds();
            // console.log(result);
            if (!result) {
                setIntervalstartRobot = 1
                robotputinnum += 1
                lutinrobotRuntime()
            }
        }
    }, 1000);

}

function isWithin30Seconds() {
    // 获取当前时间的时间戳（以毫秒为单位）
    var currentTimestamp = Date.now();

    // 计算当前时间戳与给定时间戳之间的差值（以毫秒为单位）
    var difference = currentTimestamp - prevtimestampRobot;

    // 将差值转换为秒数
    var differenceInSeconds = Math.abs(difference / 1000);

    // 检查差值是否在 30 秒之内
    return differenceInSeconds <= 30;
}

// 调用函数开始执行
runEverySecond();

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    if (msg.action == "resRobotKeyword") {
        conditionForm = msg.data
        console.log(conditionForm);
        collectionData = []
        urlp = 1
        robotstatenum1 = 0
        robotstatenum2 = 0
        robotputinnum = 0
        errorrobotputinnum = 0

        let popupcontainer = document.getElementsByClassName("popup-lutianrobot-container")
        if (popupcontainer.length > 0) {
            popupcontainer[0].remove()
        }
        flowOperation()
    } else if (msg.action == "getcookiedataLutinrobot") {
        var currentTime = new Date();
        prevtimestampRobot = currentTime.getTime();
        setIntervalstartRobot = 0

        let robotputinnumcopy = robotputinnum + 1
        let popupul = document.querySelector('.popup-lutianrobot-container .popupul')
        let popupdiv = document.querySelector('.popup-lutianrobot-container .popupdiv')
        let str1 = `（计划投放${collectionData.length}条数据，当前已投放${robotputinnumcopy * robotputinsize >= collectionData.length ? collectionData.length - errorrobotputinnum : robotputinnumcopy * robotputinsize - errorrobotputinnum}条数据）`
        let lis = document.querySelectorAll(".popupul li")
        if (lis.length > 0) {
            if (lis[lis.length - 1].innerText != `第${robotputinnumcopy}组数据机器人广告投放失败`) {
                let liElement = document.createElement('li');
                liElement.textContent = `第${robotputinnumcopy}组数据机器人广告投放成功`;
                popupul.appendChild(liElement);
                popupul.scrollTop = popupul.scrollHeight;
            }
        } else {
            let liElement = document.createElement('li');
            liElement.textContent = `第${robotputinnumcopy}组数据机器人广告投放成功`;
            popupul.appendChild(liElement);
            popupul.scrollTop = popupul.scrollHeight;
        }
        popupdiv.innerHTML = str1
        robotputinnum += 1
        lutinrobotRuntime()
    } else if (msg.action == "getcookiedataLutinrobotno") {
        var currentTime = new Date();
        prevtimestampRobot = currentTime.getTime();
        setIntervalstartRobot = 0

        console.log('错误');
        let robotputinnumcopy = robotputinnum + 1
        errorrobotputinnum += msg.data
        let popupul = document.querySelector('.popup-lutianrobot-container .popupul')
        let popupdiv = document.querySelector('.popup-lutianrobot-container .popupdiv')
        let str1 = `（计划投放${collectionData.length}条数据，当前已投放${robotputinnumcopy * robotputinsize >= collectionData.length ? collectionData.length - errorrobotputinnum : robotputinnumcopy * robotputinsize - errorrobotputinnum}条数据）`
        let lis = document.querySelectorAll(".popupul li")
        if (lis.length > 0) {
            if (lis[lis.length - 1].innerText != `第${robotputinnumcopy}组数据机器人广告投放失败`) {
                let liElement = document.createElement('li');
                liElement.textContent = `第${robotputinnumcopy}组数据机器人广告投放失败`;
                liElement.style.color = 'red'
                popupul.appendChild(liElement);
                popupul.scrollTop = popupul.scrollHeight;
            }
        } else {
            let liElement = document.createElement('li');
            liElement.textContent = `第${robotputinnumcopy}组数据机器人广告投放失败`;
            liElement.style.color = 'red'
            popupul.appendChild(liElement);
            popupul.scrollTop = popupul.scrollHeight;
        }
        popupdiv.innerHTML = str1
        robotputinnum += 1
        lutinrobotRuntime()
    }
})

function flowOperation() {
    addLutianrobotTc().then(() => {
        addLutianrobotIfram()
    })
}

function addLutianrobotIfram() {
    let url = 'https://promote.ruten.com.tw/rtb/ad_select.php?p=' + urlp
    fetch(url)
        .then((response) => response.text())
        .then((html) => {
            addLutianrobotHtml(html).then(() => {
                addLutianrobotHtmlData()
            })

        })
        .catch((error) => {
            console.log(error);
        });
}

function addLutianrobotHtml(html) {
    return new Promise((resolve) => {
        if (robotstatenum1 == 0) {
            if (document.querySelector('.popup-lutianrobot-container-url')) {
                document.querySelector('.popup-lutianrobot-container-url').innerHTML = html;
                resolve()
            } else {
                // 创建弹窗容器元素
                var popupContainer = document.createElement('div');
                popupContainer.classList.add('popup-lutianrobot-container-url');
                popupContainer.innerHTML = html;

                // 创建样式元素
                var styleElement = document.createElement('style');
                styleElement.textContent = `
            .popup-lutianrobot-container-url {
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 400px;
                height:250px;
                overflow: auto;
                background-color: #fff;
                padding: 20px;
                box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
                border-radius: 5px;
                text-align: center;
                z-index:9998;
            }
        `;

                // 将样式元素添加到文档头部
                document.head.appendChild(styleElement);

                // 将弹窗容器添加到文档 body
                document.body.appendChild(popupContainer);

                resolve()
            }
        } else {
            resolve()
        }




    })
}

function addLutianrobotHtmlData() {
    if (robotstatenum1 == 1) {
        // addLutianrobotHtmlRecu()
        return
    }
    let doc = document.getElementsByClassName('popup-lutianrobot-container-url')[0]
    let nametd = doc.querySelectorAll('.rt-table tr:not(:first-child)')
    let datas = []
    let collectionnum = 0
    if (nametd.length > 0) {
        nametd.forEach((item, index) => {
            if (collectionnum == 1) {
                return
            }
            let statetd = item.querySelector(".item-btn").innerText
            if (statetd != '廣告進行中') {

                let title = item.querySelector(".item-name a").innerText
                let conditionstate = 0
                conditionForm.keyword.forEach((item2, index2) => {
                    if (collectionnum == 1) {
                        return
                    }
                    if (title.includes(item2)) {
                        conditionstate = 1
                    }

                    if (index2 + 1 == conditionForm.keyword.length) {
                        if (conditionstate == 0) {
                            let itemurl = item.querySelector(".item-name a").href
                            let match = itemurl.match(/\?(\d+)/);
                            // 如果找到匹配项
                            if (match !== null) {
                                var number = match[1]; // 获取匹配的数字部分
                                let a = {
                                    gno: number,
                                    title: title
                                }
                                if (collectionData.length >= conditionForm.quantity) {
                                    collectionnum = 1
                                    addLutianrobotHtmlRecu()
                                    return
                                } else {
                                    collectionData.push(a)
                                    if (nametd.length == index + 1) {
                                        addLutianrobotHtmlRecu()
                                    }
                                }
                            } else {
                                if (nametd.length == index + 1) {
                                    addLutianrobotHtmlRecu()
                                }
                            }
                        } else {
                            if (nametd.length == index + 1) {
                                addLutianrobotHtmlRecu()
                            }
                        }

                    }
                });
            } else {
                if (nametd.length == index + 1) {
                    addLutianrobotHtmlRecu()
                }
            }


        });
    } else {
        // 页面没有数据
    }
}

function addLutianrobotHtmlRecu() {
    if (robotstatenum1 == 0) {
        if (collectionData.length >= conditionForm.quantity) {
            let pElement = document.querySelector('.popup-lutianrobot-container .popupstatus');
            let pcont = document.querySelector(".popup-lutianrobot-container .content")
            let ph2 = document.querySelector(".popup-lutianrobot-container h2")
            pElement.textContent = `数据获取完成`;
            ph2.textContent = `数据获取完成`;
            pElement.style.color = "blue"
            pcont.scrollTop = pcont.scrollHeight;
            document.querySelector(".popup-lutianrobot-container button").textContent = "关闭"
            document.querySelector(".popup-lutianrobot-container button").style.backgroundColor = "#007bff"
            if (document.getElementsByClassName('popup-lutianrobot-container-url').length > 0) {
                document.getElementsByClassName('popup-lutianrobot-container-url')[0].remove()
            } else {
                setTimeout(() => {
                    if (document.getElementsByClassName('popup-lutianrobot-container-url').length > 0) {
                        document.getElementsByClassName('popup-lutianrobot-container-url')[0].remove()
                    }
                }, 1000);
            }
            let popupul = document.querySelector('.popup-lutianrobot-container .popupul')
            let popupdiv = document.querySelector('.popup-lutianrobot-container .popupdiv')
            let str1 = `（计划获取${conditionForm.quantity}条数据，当前已获取${collectionData.length}条数据）`
            let lis = document.querySelectorAll(".popupul li")
            if (lis.length > 0) {
                if (lis[lis.length - 1].innerText != `第${urlp}页数据获取成功`) {
                    let liElement = document.createElement('li');
                    liElement.textContent = `第${urlp}页数据获取成功`;
                    popupul.appendChild(liElement);
                    popupul.scrollTop = popupul.scrollHeight;
                }
            } else {
                let liElement = document.createElement('li');
                liElement.textContent = `第${urlp}页数据获取成功`;
                popupul.appendChild(liElement);
                popupul.scrollTop = popupul.scrollHeight;
            }

            popupdiv.innerHTML = str1
            collectionDataComplete()

        } else {
            let popupul = document.querySelector('.popup-lutianrobot-container .popupul')
            let popupdiv = document.querySelector('.popup-lutianrobot-container .popupdiv')
            let str1 = `（计划获取${conditionForm.quantity}条数据，当前已获取${collectionData.length}条数据）`
            let lis = document.querySelectorAll(".popupul li")
            if (lis.length > 0) {
                if (lis[lis.length - 1].innerText != `第${urlp}页数据获取成功`) {
                    let liElement = document.createElement('li');
                    liElement.textContent = `第${urlp}页数据获取成功`;
                    popupul.appendChild(liElement);
                    popupul.scrollTop = popupul.scrollHeight;
                }
            } else {
                let liElement = document.createElement('li');
                liElement.textContent = `第${urlp}页数据获取成功`;
                popupul.appendChild(liElement);
                popupul.scrollTop = popupul.scrollHeight;
            }
            popupdiv.innerHTML = str1
            setTimeout(() => {
                urlp += 1
            }, 800);

            setTimeout(() => {
                addLutianrobotIfram()
            }, 1500);
        }
    } else {
        // collectionDataComplete()

    }

}



function addLutianrobotTc() {
    return new Promise((resolve) => {
        // 创建弹窗容器元素
        var popupContainer = document.createElement('div');
        popupContainer.classList.add('popup-lutianrobot-container');

        // 创建弹窗标题元素
        var popupTitle = document.createElement('h2');
        popupTitle.style.fontSize = '22px';
        popupTitle.style.fontWeight = '800';
        popupTitle.textContent = '获取商品信息';
        popupContainer.appendChild(popupTitle);

        // 创建弹窗消息元素
        var popupMessage = document.createElement('div');
        popupMessage.classList.add('content');
        popupContainer.appendChild(popupMessage);

        var popupdiv = document.createElement('div');
        popupdiv.classList.add('popupdiv');
        popupdiv.style.marginBottom = '10px'
        popupdiv.style.marginLeft = '40px'
        popupdiv.style.display = 'flex'
        popupdiv.style.fontWeight = '700'
        popupMessage.appendChild(popupdiv);

        // ul
        var popupul = document.createElement('ul');
        popupul.classList.add('popupul');
        popupMessage.appendChild(popupul);

        // p
        var popupp = document.createElement('p');
        popupp.classList.add('popupstatus');
        popupp.textContent = '获取商品信息中...';
        popupMessage.appendChild(popupp);


        // 创建关闭按钮元素
        var closeButton = document.createElement('button');
        closeButton.classList.add('popupstatus_button');
        closeButton.textContent = '关闭并停止获取';




        // 添加关闭按钮的点击事件处理函数
        closeButton.addEventListener('click', function () {
            robotstatenum1 = 1
            robotstatenum2 = 1
            setTimeout(() => {
                popupContainer.remove()
                if (document.getElementsByClassName('popup-lutianrobot-container-url').length > 0) {
                    document.getElementsByClassName('popup-lutianrobot-container-url')[0].remove()
                } else {
                    setTimeout(() => {
                        if (document.getElementsByClassName('popup-lutianrobot-container-url').length > 0) {
                            document.getElementsByClassName('popup-lutianrobot-container-url')[0].remove()
                        }
                    }, 1000);
                }
            }, 500);


        });

        // 将关闭按钮添加到弹窗容器中
        popupContainer.appendChild(closeButton);

        // 创建样式元素
        var styleElement = document.createElement('style');
        styleElement.textContent = `
    .popup-lutianrobot-container {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 600px;
        height:350px;
        background-color: #fff;
        padding: 20px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
        border-radius: 5px;
        text-align: center;
        z-index:9999;
    }

    .popup-lutianrobot-container h2 {
        margin-top: 0;
    }

    .popup-lutianrobot-container .content {
        margin-bottom: 20px;
        margin-top:20px;
        height:190px;
    }
    .popup-lutianrobot-container .content .popupul{
        margin-left:20px;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        min-height: 0;
        max-height: 170px;
        overflow: auto;
    }
    .popup-lutianrobot-container .content .popupstatus{
        text-align: left;
        margin-left: 20px;
        font-size: 14px;
        color: red;
    }
    .popup-lutianrobot-container .content .popupul li{
        font-size:13px;
        font-size: 13px;
        margin-top: 2px;
        margin-bottom: 2px;
    }

    .popup-lutianrobot-container button {
        padding: 10px 20px;
        background-color: red;
        color: #fff;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }
`;

        // 将样式元素添加到文档头部
        document.head.appendChild(styleElement);

        // 将弹窗容器添加到文档 body
        document.body.appendChild(popupContainer);

        resolve()
    })

}

function collectionDataComplete() {
    changerobotPopupText().then(() => {
        console.log(collectionData);
        lutinrobotRuntime()

    })
}

function lutinrobotRuntime() {
    if (robotstatenum2 == 0) {
        let cookies = document.cookie;
        let user = document.querySelector(".rt-header-inner .rt-header-part .rt-header-login .rt-header-loaded .rt-header-topnav-link").innerText
        let start = robotputinnum * robotputinsize;
        let end = start + robotputinsize;
        let slicedata = collectionData.slice(start, end)
        if (slicedata.length > 0) {
            var gnoArray = slicedata.map(function (obj) {
                return obj.gno;
            });

            // 使用join方法将id值用逗号分隔成一个字符串
            var idString = gnoArray.join(',');
            try {
                let data = {
                    action: 'rescookiedataLutinrobot',
                    cookies: cookies,
                    user: user,
                    data: idString,
                    offer: conditionForm.offer,
                    robotputinnum: robotputinnum
                }
                chrome.runtime.sendMessage({ data }, function (response) {
                    if (response) {
                    }
                });
            } catch (err) {
                console.log(err);
            }
        } else {
            prevtimestampRobot = 0;
            setIntervalstartRobot = 0

            collectionData = []
            conditionForm = {}
            urlp = 1
            robotstatenum1 = 0
            robotstatenum2 = 0
            robotputinnum = 0
            errorrobotputinnum = 0

            console.log('投放完成');
            let pElement = document.querySelector('.popup-lutianrobot-container .popupstatus');
            let pcont = document.querySelector(".popup-lutianrobot-container .content")
            let ph2 = document.querySelector(".popup-lutianrobot-container h2")
            pElement.textContent = `机器人广告投放完成`;
            ph2.textContent = `机器人广告投放完成`;
            pElement.style.color = "blue"
            pcont.scrollTop = pcont.scrollHeight;
            document.querySelector(".popup-lutianrobot-container button").textContent = "关闭"
            document.querySelector(".popup-lutianrobot-container button").style.backgroundColor = "#007bff"
            if (document.getElementsByClassName('popup-lutianrobot-container-url').length > 0) {
                document.getElementsByClassName('popup-lutianrobot-container-url')[0].remove()
            } else {
                setTimeout(() => {
                    if (document.getElementsByClassName('popup-lutianrobot-container-url').length > 0) {
                        document.getElementsByClassName('popup-lutianrobot-container-url')[0].remove()
                    }
                }, 1000);
            }

        }
    }



}

function changerobotPopupText() {
    return new Promise((resolve, reject) => {
        document.querySelector(".popup-lutianrobot-container h2").innerText = '机器人广告投放中'
        document.querySelector(".popup-lutianrobot-container .popupdiv").innerText = ''
        document.querySelector(".popup-lutianrobot-container .popupul").innerHTML = ''
        document.querySelector(".popup-lutianrobot-container .popupstatus").innerHTML = '机器人广告投放中...'
        document.querySelector(".popup-lutianrobot-container .popupstatus").style.color = 'red'
        document.querySelector(".popup-lutianrobot-container .popupstatus_button").innerHTML = '关闭并停止投放'
        document.querySelector(".popup-lutianrobot-container .popupstatus_button").style.backgroundColor = 'red'
        setTimeout(() => {
            resolve()
        }, 1000);

    })
}

